<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redis;
use DB;

class CheckQrKey
{
    public function handle($request, Closure $next)
    {
        if(!request('qrKey')) {
            return error('未授权访问');
        }
        $qrKey = request('qrKey');
        $info = $this->getMemberInfoByQrKey($qrKey);
        if(!$info) {
            return error('二维码已被变更失效，请联系账户持有人');
        }
        $GLOBALS['xcx_openid'] = $info['xcx_openid'];
        $GLOBALS['wx_openid'] = $info['wx_openid'];
        $GLOBALS['shop_id'] = $info['shop_id'];
        $GLOBALS['mid'] = $info['id'];
        $GLOBALS['admin_id'] = $info['admin_id'];

        return $next($request);
    }

    public function getMemberInfoByQrKey($qrKey)
    {
        $member = DB::table('member')->where('qr_key', $qrKey)->first();
        if(!$member) {
            return false;
        }
        return object_to_array($member);
    }
}